<?php

namespace app\common\model;

use app\common\constants\DBConstant;
use app\common\util\CommonUtil;
use think\facade\Cache;
use think\Model;

/**
 * 销售带看房
 */
class SellerAppointment extends BaseModel
{

    // 表名,不含前缀
    protected $name = 'seller_appointment';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';
    // 定义时间戳字段名
    protected $updateTime = false;


    public function house()
    {
        return $this->belongsTo("house", "house_id")->setEagerlyType(0);
    }

    public function user()
    {
        return $this->belongsTo("user", "user_id")->setEagerlyType(0);
    }


    private function _decodeData($findData)
    {

        $findData['photos'] = CommonUtil::splitArr($findData['photos'], DBConstant::TABLE_FIELD_JOIN_SYMBOL);
        $tempPhotos = (new Attachment())->whereIn("id", $findData['photos'])->field(['id', 'url'])->select()->toArray();
        $findData['photoList'] = [];
        foreach ($tempPhotos as $key => $value) {
            $tempPhotos[$key]['url'] = CommonUtil::formatHostUrl($value['url']);
        }
        $findData['photoList'] = $tempPhotos;
        $findData['house'] = model('house')->selectById($findData['house_id'], true);
        $userInfo = model('user')->findById($findData['user_id']);
        $findData['user'] = [
            'id' => $userInfo['id'],
            'nickname' => $userInfo['nickname'],
            'phone' => $userInfo['phone'],
            'wx_avatar' => $userInfo['wx_avatar']
        ];
        return $findData;
    }


    public function findByUserId($userId, $start_time, $end_time, $page = 1, $limit = 10)
    {
        $query = $this->where("user_id", $userId);
        if (!empty($start_time)) {
            $query->where("create_time", ">=", $start_time);
        }
        if (!empty($end_time)) {
            $query->where("create_time", "<=", date('Y-m-d 23:59:59',strtotime($end_time)));
        }
        $dataList = $query->order("id", "desc")->page($page, $limit)->select();
        if (empty($dataList)) return [];
        foreach ($dataList as $key => $value) {
            $dataList[$key]['house'] = model("house")->selectById($value['house_id'], true);
        };
        return $dataList;
    }

    public function selectById($id)
    {
        $findData = $this->findById($id);
        return $this->_decodeData($findData);
    }

    public function getStatusList()
    {
        return [
            [
                'id' => 1,
                'title' => '申请中',
            ],
            [
                'id' => 2,
                'title' => '带看中',
            ],
            [
                'id' => 3,
                'title' => '已完成',
            ],
        ];
    }


}
